#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :guotie_jd_main.py
# Time  :2024/12/11 16:04
# Email :fortunatedong@163.com
# Author:by Adonli
import random
import sys
import time
from datetime import datetime,timedelta
import json
import toml
from playwright.sync_api import sync_playwright
from jingdong_order_synchronization_kuaipu_zhuzhanghao.get_jingdong_cookies import jingdong_login
from jingdong_order_synchronization_kuaipu_zhuzhanghao.get_jingdong_messages.get_jingdong_delete_order import \
    get_jingdong_delete_order_datas
from jingdong_order_synchronization_kuaipu_zhuzhanghao.settings.logger import Loggings

from jingdong_order_synchronization_kuaipu_zhuzhanghao.get_jingdong_messages.get_jingdong_order import get_jingdong_order_datas
from jingdong_order_synchronization_kuaipu_zhuzhanghao.dingding_robot.messages_push import MessagePush
logs = Loggings()

def run_main():
    count = 0
    while count < 10:
        try:

            retry_dict_data = {"code": 3,
                               "status":"success",
                               "result": "正在加载最新COOKIE",
                               "update": "程序正常运行"}
            MessagePush(retry_dict_data).admin_info_text_push()

            with open("auth/jingdong_cookies.json", "r") as f:
                cookie_data = json.load(f)
                jsessionid_list = []
                # for cookie in cookie_data:
                #     print(cookie)
                #     if cookie["name"] == "JSESSIONID":
                #         print(cookie["value"])
                JSESSIONID = [cookie["value"] for cookie in cookie_data if cookie["name"] == "JSESSIONID"]
                flash = [cookie["value"] for cookie in cookie_data if cookie["name"] == "flash"]
                jingdong_cookie = f"flash={random.choice(flash)};JSESSIONID={random.choice(JSESSIONID)};"
            # print(jingdong_cookie)

            while True:
                current_time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                logs.info(f"当前时间：{current_time_str}")

                cfg = toml.load('settings/config.toml')
                guangzhou_zong_username = cfg['LOGINUSER']['guangzhou_zong_username']
                guangzhou_zong_password = cfg['LOGINUSER']['guangzhou_zong_password']
                last_end_run_time_str = cfg['RUNTIME']['last_end_run_time']
                last_start_run_time_str = cfg['RUNTIME']['last_start_run_time']

                last_end_run_time = datetime.strptime(last_end_run_time_str, "%Y-%m-%d %H:%M:%S")
                last_start_run_time = datetime.strptime(last_start_run_time_str, "%Y-%m-%d %H:%M:%S")
                current_time = datetime.strptime(current_time_str, "%Y-%m-%d %H:%M:%S")

                logs.info(f"上一次结束时间：{last_end_run_time}")
                logs.info(f"上一次开始时间：{last_start_run_time}")

                # 计算当前时间与上一次运行时间的差值（秒）
                time_diff_seconds = (current_time - last_end_run_time).total_seconds()

                # 如果时间差超过10分钟（600秒）
                if time_diff_seconds >= 600:
                    # 计算需要向前推进的时间（秒）
                    advance_seconds = time_diff_seconds - (time_diff_seconds % 600)  # 取整到最近的600秒倍数

                    # 更新结束时间和开始时间，保持3天的时间差
                    new_end_time = last_end_run_time + timedelta(seconds=advance_seconds)
                    new_start_time = last_start_run_time + timedelta(seconds=advance_seconds)

                    # 转换为字符串格式
                    new_end_time_str = new_end_time.strftime("%Y-%m-%d %H:%M:%S")
                    new_start_time_str = new_start_time.strftime("%Y-%m-%d %H:%M:%S")
                    # 调用同步函数
                    # get_jingdong_order_datas(
                    #     guangzhou_zong_username,
                    #     guangzhou_zong_password,
                    #     new_start_time_str,
                    #     new_end_time_str,
                    #     jingdong_cookie
                    # ).synchronization_kuaipu_order()
                    payload = {
                        "startTime": new_start_time_str,
                        "endTime": new_end_time_str,
                        "_search": "false",
                        "nd": int(round(time.time() * 1000)),
                        "rows": 100,
                        "page": 1,
                        "sidx": "orderId asc, groupString asc,",
                        "sord": "asc",
                        "orderId": "",
                        "sku": "",
                        "poId": "",
                        "roId": "",
                        "shipNo": "",
                        "phone": "",
                        "orderState": 7,
                        "businessType": "",
                        "pin": "",
                        "paymentType": "",
                        "vendorStoreId": "",
                        "ouId": "",
                    }
                    get_jingdong_order_datas(
                        guangzhou_zong_username,
                        guangzhou_zong_password,
                        jingdong_cookie,
                        payload
                    ).synchronization_kuaipu_order()


                    get_jingdong_delete_order_datas(guangzhou_zong_username,
                                                    guangzhou_zong_password,
                                                    new_start_time_str,
                                                    new_end_time_str,
                                                    jingdong_cookie
                                                    ).delete_jingdong_order()
                    # 更新配置文件中的时间
                    cfg['RUNTIME']['last_end_run_time'] = new_end_time_str
                    cfg['RUNTIME']['last_start_run_time'] = new_start_time_str

                    with open('settings/config.toml', 'w',encoding="utf-8") as f:
                        toml.dump(cfg, f)

                    logs.info(f"已更新结束时间为：{new_end_time_str}")
                    logs.info(f"已更新开始时间为：{new_start_time_str}")

                    wait_seconds = 600 - (datetime.strptime(datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                                            "%Y-%m-%d %H:%M:%S") - new_end_time).total_seconds()
                    logs.info(f"同步完成，等待时间：{wait_seconds}秒")
                    time.sleep(wait_seconds)
                else:
                    # 如果时间差小于150秒，等待剩余时间
                    wait_seconds = max(0, int(600 - time_diff_seconds))
                    logs.info(f"未到同步时间，等待：{wait_seconds}秒")
                    time.sleep(wait_seconds)
        except Exception as e:
            exc_type, exc_obj, tb = sys.exc_info()
            filename = tb.tb_frame.f_code.co_filename
            lineno = tb.tb_lineno
            logs.error(f'捕获到异常信息:{e};异常类型: {exc_type.__name__};文件名: {filename};行号: {lineno};')
            error_dict_data = {"code": 2, "result": "程序运行异常",
                               "error": f"在{filename}文件中{lineno}行出错：异常类型: {exc_type.__name__}、异常描述: {e}",
                               "retry": "内循环重试次数已达到最大值3次，操作失败。",
                               "update": "正在自动登录京东,获取最新COOKIES,程序稍后自动重启"}
            MessagePush(error_dict_data).admin_error_text_push()
            with sync_playwright() as pw:
                update_cookies_dict_data = jingdong_login(pw).save_jingdong_cookie()
            MessagePush(update_cookies_dict_data).admin_info_text_push()
            if update_cookies_dict_data["status"] == "failed":
                sys.exit(0)
            count += 1

if __name__ == '__main__':
    run_main()